package com.wangyb.wework.service.contact;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wangyb.wework.bo.ContactAddwayState;
import com.wangyb.wework.enums.ContactAddwayStateEnum;
import com.wangyb.wework.entity.contact.WwContact;
import com.wangyb.wework.entity.contact.WwContactEmployee;
import com.wangyb.wework.entity.employee.WwEmployee;
import com.wangyb.wework.exception.CommonException;
import com.wangyb.wework.mapper.contact.WwContactEmployeeMapper;
import com.wangyb.wework.service.IWwEmployeeService;
import com.wangyb.wework.utils.FileUtils;
import com.wangyb.wework.utils.MediaCacheUtils;
import com.wangyb.wework.utils.WxApiUtils;
import com.wangyb.wework.utils.ali.AliyunOssUtils;
import com.wangyb.wework.vo.MeidaVo;
import com.wangyb.wework.wxApi.BaseWxResp;
import com.wangyb.wework.wxApi.CreateContactWayResp;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.xhtmlrenderer.swing.Java2DRenderer;
import org.xhtmlrenderer.util.FSImageWriter;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

/**
 * @Author: wangyb
 * @Date: 2021/7/1 1:03 下午
 */
@Service
@Slf4j
public class WwContactEmployeeServiceImpl extends ServiceImpl<WwContactEmployeeMapper, WwContactEmployee> implements IWwContactEmployeeService{
	@Autowired
	private IWwContactService iWwContactService;
	@Autowired
	private IWwEmployeeService iWwEmployeeService;
	@Autowired
	private SpringTemplateEngine templateEngine;
	@Autowired
	private IWwContactEmployeeService iWwContactEmployeeService;

	private final static String QR_CODE_CARD_TEMPLATE = "QrCodeCard.html";


	@Override
	public MeidaVo getQrCodeCardUrl(WwEmployee employee, WwContact contact, boolean refreshAvatar){
		WwContactEmployee contactEmployee = iWwContactEmployeeService.lambdaQuery()
			.eq(WwContactEmployee::getContactId, contact.getId())
			.eq(WwContactEmployee::getEmployeeId, employee.getId())
			.one();
		if (contactEmployee == null ){
			//TODO 这里有可能客户-员工表没有同步更新，需处理
		}

		if (refreshAvatar){
			//TODO 刷新员工头像
		}
		//从缓存中取
		String ossFileKey = contactEmployee.getQrCode();
		if (StringUtils.isNotBlank(ossFileKey)){
			MeidaVo media= new MeidaVo();
			String mediaId = MediaCacheUtils.getMediaId(ossFileKey);
			if (mediaId == null){
				//缓存已过期，没有取到mediaId,则需重新上传临时素材并缓存mediaId
				File file = AliyunOssUtils.getFile(ossFileKey);
				mediaId = WxApiUtils.uploadFileToTemp(employee.getCorpId(), "image", file);
				file.delete();
				MediaCacheUtils.cacheMediaId(ossFileKey,mediaId);
			}
			media.setMediaId(mediaId);
			media.setUrl(AliyunOssUtils.getUrl(ossFileKey));
			return media;
		}
		//重新创建
		return this.createQrCode(employee,contact, contactEmployee);
	}

	/**
	 * 创建名片并上传到企业微信素材中
	 * @param employee
	 * @param contact
	 * @return 素材media_id,和url
	 */
	private MeidaVo createQrCode(WwEmployee employee, WwContact contact,WwContactEmployee contactEmployee){
		String configId = contactEmployee.getConfigId();
		Long corpId = employee.getCorpId();
		String wxQrCodeUrl = null;
		if (StringUtils.isBlank(configId)){
			ContactAddwayState state = new ContactAddwayState(ContactAddwayStateEnum.YiKeYiMa,contactEmployee.getId());
			Set<String> wxUserIdSet = new HashSet<>();
			wxUserIdSet.add(employee.getWxUserId());
			CreateContactWayResp resp = WxApiUtils.requestCreateContactWay(corpId, true, state, wxUserIdSet);
			wxQrCodeUrl = resp.getQrCode();
			configId = resp.getConfigId();
		}else{
			BaseWxResp resp = WxApiUtils.requestGetContactWay(corpId,configId);
			wxQrCodeUrl = JSONObject.parseObject(resp.get("contact_way")).getString("qr_code");
		}

		File file = createQrCodeCardFile(contact,employee,wxQrCodeUrl);
		String ossFileKey = String.format("yikeyima/%s/%s-%s.png",corpId,employee.getId(),contact.getId());
		AliyunOssUtils.upLoad(file,ossFileKey);
		String mediaId = WxApiUtils.uploadFileToTemp(corpId,"image",file);
		MediaCacheUtils.cacheMediaId(ossFileKey,mediaId);
		file.delete();
		MeidaVo mediaVo = new MeidaVo();
		mediaVo.setMediaId(mediaId);
		mediaVo.setUrl(AliyunOssUtils.getUrl(ossFileKey));
		iWwContactEmployeeService.lambdaUpdate()
			.set(StringUtils.isNotBlank(configId),WwContactEmployee::getConfigId,configId)
			.set(WwContactEmployee::getQrCode,ossFileKey)
			.eq(WwContactEmployee::getId,contactEmployee.getId())
			.update();
		return mediaVo;
	}

	/**
	 * 创建一客一码 名片，生成名片文件
	 * @param contact
	 * @param employee
	 * @param qrCodeUrl
	 * @return
	 */
	private File createQrCodeCardFile(WwContact contact, WwEmployee employee,String qrCodeUrl){
		String corpName = "学府考研";
		String avatarUrl = AliyunOssUtils.getUrl(employee.getThumbAvatar());
		Context context = new Context();
		context.setVariable("avatarUrl",avatarUrl);
		context.setVariable("name",employee.getName());
		context.setVariable("qrCodeUrl",qrCodeUrl);
		context.setVariable("corpName",corpName);
		try {
			File tempHtmlFile = File.createTempFile("temp"+ FileUtils.getRandomString(),".html");
			File tempImgFile = File.createTempFile("temp"+FileUtils.getRandomString(),".png");
			FileWriter writer = new FileWriter(tempHtmlFile);
			templateEngine.process(QR_CODE_CARD_TEMPLATE,context,writer);
			writer.close();
			log.debug(tempHtmlFile.getAbsolutePath());
			final Java2DRenderer renderer = new Java2DRenderer(tempHtmlFile.getAbsolutePath(), 320, 390);
			final BufferedImage img = renderer.getImage();
			final FSImageWriter imageWriter = new FSImageWriter();
			imageWriter.setWriteCompressionQuality(0.9f);
			imageWriter.write(img, tempImgFile.getAbsolutePath());
			tempHtmlFile.delete();
			return tempImgFile;
		} catch (IOException e) {
			log.debug(e.getMessage());
			throw new CommonException("创建名片失败");
		}
	}
	@Override
	public boolean restore(String contactWxUserid, String employeeWxUserid){
		return this.getBaseMapper().restore(contactWxUserid,employeeWxUserid);
	}

}
